package com.cdm.domain.service;

import java.sql.Timestamp;
import java.util.List;

import net.sf.frails.JSFHelper;

import com.cdm.domain.dao.ContentDAO;
import com.cdm.domain.dao.ContentTypeDAO;
import com.cdm.domain.dao.SequenceDAO;
import com.cdm.domain.dao.UserDAO;
import com.cdm.persistence.Content;
import com.cdm.persistence.ContentState;
import com.cdm.persistence.ContentType;
import com.cdm.persistence.EntityManagerHelper;
import com.cdm.persistence.User;
import com.cdm.util.IdGenerator;
import com.vivo.exception.DToolCheckException;
import com.vivo.util.DTool;

public class ServiceImpl implements Service {
	private static DTool D = new DTool(DTool.DEBUG);

	public User login(String name, String password, String ip) {
		D.check(null == name || name.length() <= 0, new DToolCheckException("name Can't be null or empty!"));
		D.check(null == password || password.length() <= 0, new DToolCheckException("password Can't be empty!"));
		D.debug("Login With Username " + name + ", password " + password);
		User user = userDAO.findByLoginAndPassword(name, password);
		if (null != user) {
			return user;
		}
		return null;
	}

	public static void main(String[] args) {
		ServiceImpl service = new ServiceImpl();
		User login = service.login("vivo", "123456", "");
		if (login != null) {
			System.out.println(login.getLoginName());
		}
	}

	public void delete(User user) {
		try {
			EntityManagerHelper.beginTransaction();
			userDAO.delete(EntityManagerHelper.getEntityManager().merge(user));
			EntityManagerHelper.commit();
		} catch (Exception ex) {
			try {
				JSFHelper.addMessage(ex.getLocalizedMessage());
				EntityManagerHelper.getEntityManager().getTransaction().rollback();
			} catch (Exception e) {
				JSFHelper.addMessage(e.getLocalizedMessage());
			}
		} finally {
			EntityManagerHelper.closeEntityManager();
		}
	}

	public void auth(User user) {
		try {
			EntityManagerHelper.beginTransaction();
			user.setAuthStatus(User.AUTHED);
			userDAO.update(user);
			EntityManagerHelper.commit();
		} catch (Exception ex) {
			try {
				JSFHelper.addMessage(ex.getLocalizedMessage());
				EntityManagerHelper.getEntityManager().getTransaction().rollback();
			} catch (Exception e) {
				JSFHelper.addMessage(e.getLocalizedMessage());
			}
		} finally {
			EntityManagerHelper.closeEntityManager();
		}
	}

	public void changeContentState(Content content, Integer state) {
		try {
			EntityManagerHelper.beginTransaction();
			content.getContentState().setContentState(state);
			contentDAO.update(content);
			EntityManagerHelper.commit();
		} catch (Exception ex) {
			try {
				JSFHelper.addMessage(ex.getLocalizedMessage());
				EntityManagerHelper.getEntityManager().getTransaction().rollback();
			} catch (Exception e) {
				JSFHelper.addMessage(e.getLocalizedMessage());
			}
		} finally {
			EntityManagerHelper.closeEntityManager();
		}
	}

	/**
	 * @deprecated
	 */
	public List<User> getAllCPs() {
		return userDAO.getByProperty(UserDAO.USER_ROLE, User.ROLE_CP);
	}

	@SuppressWarnings("unchecked")
	public List<User> getAuthedUsersByRole(int role) {
		return (List<User>) EntityManagerHelper.getEntityManager().createQuery("from User user where authStatus = 0 and userRole = ?")
		        .setParameter(1, role).getResultList();
	}

	public List<ContentType> getAllContentTypes() {
		return contentTypeDAO.findAll();
	}

	public void createContent(Content content, User loginUser, int state) {
		try {
			EntityManagerHelper.beginTransaction();
			content.setCp(loginUser);
			long dcid = IdGenerator.generateDCID(0l, 0001l, 0xffl);// TODO How to Contribute Content Type
			content.setDcid(dcid);
			content.setContentState(new ContentState(dcid, state));
			contentDAO.save(content);
			JSFHelper.addMessage("message_create_content_success");
			EntityManagerHelper.commit();
		} catch (Exception ex) {
			try {
				JSFHelper.addMessage(ex.getLocalizedMessage());
				EntityManagerHelper.getEntityManager().getTransaction().rollback();
			} catch (Exception e) {
				JSFHelper.addMessage(e.getLocalizedMessage());
			}
		} finally {
			EntityManagerHelper.closeEntityManager();
		}
	}

	/*
	 * DAOs
	 */
	private SequenceDAO sequenceDAO = new SequenceDAO();
	private UserDAO userDAO = new UserDAO();
	private ContentDAO contentDAO = new ContentDAO();
	private ContentTypeDAO contentTypeDAO = new ContentTypeDAO();

}
